package com.jt808.gateway.mocktest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;

import java.net.InetSocketAddress;


public class JT808Server {
    private final int port = 35100;


    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();//用于接收连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();//用于处理连接

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)//指定通道类型
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 按换行符分帧（需与客户端约定分隔符）
                            // 修改服务端分隔符为 0x7E
                            ByteBuf delimiter = Unpooled.wrappedBuffer(new byte[]{0x7E});
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, true, false, delimiter));
                            // 1. 自定义分帧解码器（保留首尾0x7E）
//                            ch.pipeline().addLast(new JT808FrameDecoder());
////                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
////                                    Unpooled.wrappedBuffer("\n".getBytes())));//
//                            ch.pipeline().addLast(new JT808Decode());//添加解码器
//                            ch.pipeline().addLast(new DataProcessor());//添加业务处理器
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)//设置连接队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true);//保持长连接

            ChannelFuture f = b.bind(new InetSocketAddress("localhost", port)).sync();
            System.out.println("jt808 Server started on port:" + port);
            f.channel().closeFuture().sync();//等待服务关闭

        } finally {
            System.out.println("线程池关闭");
            workerGroup.shutdownGracefully();//优雅关闭线程池
            bossGroup.shutdownGracefully();//优雅关闭线程池
        }
    }

    public static void main(String[] args) {

        try {

            new JT808Server().start();//从命令行参数获取端口号并启动服务

        } catch (Exception e) {

            e.printStackTrace();

        }

    }
}
